import './index.less';
import * as echarts from 'echarts';
import {option} from "./option.ts";
import {useEffect, useRef, useState} from "react";
import useAppState from "../../store";
import COLOR_SCALES_ARRAY from "../../constant.ts"
import {isEmpty} from "lodash";

const LineGraph = () => {
    // 使用 useRef 持久化保存 ECharts 实例
    const chartRef = useRef<echarts.ECharts | null>(null);
    const chartContainerRef = useRef<HTMLDivElement | null>(null);
    const {themeDateData, topicHeat} = useAppState();
    useEffect(() => {
        // 初始化逻辑（仅执行一次）
        if (!chartRef.current && chartContainerRef.current) {
            // 1. 初始化图表
            chartRef.current = echarts.init(chartContainerRef.current);

            // 2. 添加窗口自适应监听
            const resizeHandler = () => chartRef.current?.resize();
            window.addEventListener('resize', resizeHandler);
            // 3. 组件卸载时的清理函数
            return () => {
                window.removeEventListener('resize', resizeHandler);
                chartRef.current?.dispose();
                chartRef.current = null;
            };
        }
    }, []);

    useEffect(() => {
        if (isEmpty(themeDateData)) return;
        if (chartRef.current) {
            const legendWidth = 100, firstGraphLeft = 40, secondGraphLeft = 80;
            const {width, height} = chartContainerRef.current.getBoundingClientRect();
            const gridWidth = Math.floor((width - legendWidth - firstGraphLeft - secondGraphLeft) / 2);
            option.grid[0].left = firstGraphLeft;
            option.grid[1].left = secondGraphLeft + gridWidth + firstGraphLeft;
            option.title[1].left = secondGraphLeft + gridWidth;

            option.grid[0].width = gridWidth;
            option.grid[1].width = gridWidth;

            option.color = themeDateData.map((item => COLOR_SCALES_ARRAY[item.theme][4]));;
            const topics = themeDateData.map((item => `Topic ${item.theme}`));
            const series = []
            const xData = Object.keys(topicHeat[topics[0].split(" ")[1]]).map(item => item.split(" ")[0]);
            topics.map(item => {
                const currentTopic = item.split(" ")[1];
                const tempData = topicHeat[currentTopic];
                series.push({
                    name: item,
                    type: 'line',
                    smooth: true,
                    data: Object.keys(tempData).map(item => tempData[item]["Frequency"]),
                    xAxisIndex: 0, // 使用第一个 x 轴
                    yAxisIndex: 0  // 使用第一个 y 轴
                })
                series.push({
                    name: item,
                    type: 'line',
                    smooth: true,
                    data: Object.keys(tempData).map(item => tempData[item]["Moving_Avg_Heat"]),
                    xAxisIndex: 1, // 使用第一个 x 轴
                    yAxisIndex: 1  // 使用第一个 y 轴
                })
            })
            option.legend.data=topics;
            option.xAxis[0].data=xData;
            option.xAxis[1].data=xData;
            option.series=series;
            // 使用 setOption 更新配置而非重新初始化
            chartRef.current.setOption(option, { notMerge: true });
        }
        return ()=>{
            if(chartRef.current) {
                option.xAxis[0].data=[]
                option.xAxis[1].data=[]
                option.series=[]
            }
        }
    }, [themeDateData]); // 依赖 testData 的变化

    return (
        <div
            id="LineGraph"
            ref={(el) => {
                chartContainerRef.current = el;
            }}
        />
    );
};

export default LineGraph;
